package nio.channel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
//输入加输出
public class channelDemo_3 {
    public static void main(String[] args) throws IOException {
        //创建输入流
        FileInputStream fileInputStream = new FileInputStream("1.txt");
        FileChannel channel = fileInputStream.getChannel();
        //创建输出流
        FileOutputStream fileOutputStream = new FileOutputStream("2.txt");
        FileChannel channel1 = fileOutputStream.getChannel();

        ByteBuffer byteBuffer1 = ByteBuffer.allocate(512);
        while (true){
            byteBuffer1.clear();
            int read = channel.read(byteBuffer1);
            if (read == -1){
                break;
            }
            byte[] array = byteBuffer1.array();
            System.out.println(new String(array));
            byteBuffer1.flip();
            channel1.write(byteBuffer1);

            ByteBuffer byteBuffer2 = ByteBuffer.allocate(512);
            String str = "你好呀";
            byte[] bytes = str.getBytes();
            for (byte b : bytes){
                byteBuffer2.put(b);
            }
            byteBuffer2.flip();
            channel1.write(byteBuffer2);
        }

        channel.close();
        channel1.close();

    }

}
